package com.ruoyi.business.youdaoController.shangyou;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.services.HttpService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.EncrypDES;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.OtherUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.vo.R;
import com.ruoyi.system.protocol.IDynamicSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * 百度->阿里
 */
@RestController
@RequestMapping("ownBdToAliApi")
public class BDToALIController {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private HttpService httpService;
    @Autowired
    private IDynamicSearchService dynamicSearchService;

    private final static String CLASSESEN = "youdao";


    //wifi回调地址
    private final static String CALLBACK_URLBASE = "http://c2.wkanx.com/tracking";



    /**
     * https://www.ssptqt.com/ownBdToAliApi/send?channelId=&dmpid=__CLICK_ID__&imeimd5=__IMEI__&oaid=__OAID__&mac=__MAC__&timestamp=__TS__&os=__OS_TYPE__&ip=__IP__&ua=__UA__&callback_url=__CALLBACK_URL__
     *百度->阿里
     * @param request
     * @return
     * @throws Exception
     */
    @Log(title = "有道", businessType = BusinessType.ESCALATION, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public Object send(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);

        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        String url = channelDetail.get("request_address") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);

        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{}
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{}

        String os = getMapValue(baseParamsMap, "os");

        String callbackUrl = URLDecoder.decode(baseParamsMap.get("callback_url") + "", Constants.UTF8);
        String callbackUrlRequestAddress = GetUrlParam.getRequestAddress(callbackUrl);
        String callbackUrlStaticParameters = GetUrlParam.TruncateUrlPage(callbackUrl);
        callbackUrlStaticParameters = callbackUrlStaticParameters.replace("{{ATYPE}}", "__ATYPE__").replace("{{AVALUE}}", "__AVALUE__");


        EncrypDES encrypDES = new EncrypDES();
        String callbackBase = OtherUtils.getServerUrl(request) + "ownBdToAliApi/callback/"+channelId+"/"+dmpid+"/";
        String encrypt_u = encrypDES.encrypt(callbackUrlRequestAddress);
        String nu = callbackBase + encrypt_u + "?"+callbackUrlStaticParameters;

        baseParamsMap.put("os", os.equals("2")?"android":os.equals("1")?"ios":"others");
        baseParamsMap.put("ts", baseParamsMap.get("timestamp"));
        baseParamsMap.put("callback_url", URLEncoder.encode(nu, Constants.UTF8));


        Map<String, Object> baseParamsMapTemp = new HashMap<>();
        baseParamsMapTemp.put("source", baseParamsMap.get("source"));//url中配置
        baseParamsMapTemp.put("imei", baseParamsMap.get("imeimd5"));
        baseParamsMapTemp.put("oaid", baseParamsMap.get("oaid"));
        baseParamsMapTemp.put("os", baseParamsMap.get("os"));
        baseParamsMapTemp.put("ip", baseParamsMap.get("ip"));
        baseParamsMapTemp.put("ua", baseParamsMap.get("ua"));
        baseParamsMapTemp.put("campaignId", getMapValue(baseParamsMap, "campaignId"));
        baseParamsMapTemp.put("unitId", getMapValue(baseParamsMap, "unitId"));
        baseParamsMapTemp.put("account_id", getMapValue(baseParamsMap, "account_id"));
        baseParamsMapTemp.put("callback", getMapValue(baseParamsMap, "callback_url"));


        List<String> tempList = new ArrayList<>();
        for(String key: baseParamsMapTemp.keySet()){
            String val = baseParamsMapTemp.get(key) + "";
            if("null".equals(val) || (val.startsWith("__") && val.endsWith("__"))){
                val = "";
            }
            tempList.add(key+"="+val);
        }
        String requestParameters = String.join("&", tempList);


        //https://grow-ad.9game.cn/feedback/d506ac2171354d4mdbdsemtnjymca554?source=jy_gamemanager&imei=4dddfc669bb74689b4e5aca2cb9f7323&oaid=e3ad3b79ca9643fe95a7651f6714f331&os=android&callback=&ip=&ua=&campaignld=&unitld=&account%20id=

        String uuid = IdUtils.fastSimpleUUID();
        String reqType = "click";
        if("POST".equals(requestType)){
            httpService.sendPost(requestAddress, requestParameters, null, ua, uuid, reqType);
        }else{
            httpService.sendGet(requestAddress, requestParameters, null, ua, uuid, reqType);
        }
        return R.success().msg(uuid);
    }


    @Log(title = "有道", businessType = BusinessType.CALLBACK, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/callback/{channelId}/{dmpid}/{encryptedUrl}")
    public Object send(HttpServletRequest request, @PathVariable("channelId") String channelId, @PathVariable("encryptedUrl") String encryptedUrl) throws Exception {
        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        String akey = channelDetail.get("callback_clientid") + "";

        String queryString = request.getQueryString();
        EncrypDES encrypDES = new EncrypDES();
        String requestAddress = encrypDES.decrypt(encryptedUrl);

        //获取请求参数, 并替换属性
        queryString = queryString.replace("__ATYPE__", "activate");
        queryString = queryString.replace("__AVALUE__", "0");
        String sign = DigestUtils.md5DigestAsHex((requestAddress+"?"+queryString+akey).getBytes()).toLowerCase();
        queryString = queryString + "&sign=" + sign;
        String uuid = IdUtils.fastSimpleUUID();
        String reqType = "callback";
        httpService.sendGet(requestAddress, queryString, null, null, uuid, reqType);
        return R.success();
    }


    private String getMapValue(Map<String, Object> map, String key){
        if(map == null){
            return "";
        }
        if(map.get(key) == null){
            return "";
        }
        return map.get(key)+"";
    }

}
